package com.itfreer.ui.audio.player;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.TypedArray;
import android.os.IBinder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.itfreer.ui.R;

import java.text.SimpleDateFormat;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * 声音播放控件
 */
public class PlayerView extends LinearLayout {

    private MusicService musicService;
    private SeekBar seekBar;
    private TextView musicStatus, musicTime;
    private com.itfreer.ui.base.TextView btnPlayOrPause;
    private LinearLayout delButtion;

    private SimpleDateFormat time = new SimpleDateFormat("m:ss");
    public android.os.Handler handler = new android.os.Handler();

    private OnClickListener delClickListener;

    public void setDelClickListener(OnClickListener delClickListener) {
        this.delClickListener = delClickListener;
    }

    public PlayerView(Context context) {
        super(context);
        setView(context);
    }

    public PlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setView(context);
        getAttrs(context, attrs);
    }

    public PlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setView(context);
        getAttrs(context, attrs);
    }

    private void setView(Context context) {
        View inflate = inflate(getContext(), R.layout.player_ui, this);

        seekBar = (SeekBar)inflate.findViewById(R.id.MusicSeekBar);
        musicStatus = (TextView)inflate.findViewById(R.id.MusicStatus);
        musicTime = (TextView)inflate.findViewById(R.id.MusicTime);

        btnPlayOrPause = (com.itfreer.ui.base.TextView)inflate.findViewById(R.id.BtnPlayorPause);
        btnPlayOrPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(musicService.mp.isPlaying()) {
                    musicService.stop();
                    seekBar.setProgress(0);
                } else {
                    musicService.playOrPause();
                }
            }
        });
        delButtion = inflate.findViewById(R.id.player_del);
        delButtion.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                stop();
                if(delClickListener!=null) delClickListener.onClick(view);
            }
        });
    }

    public void setReadonly(boolean readonly) {
        if(readonly) {
            delButtion.setVisibility(GONE);
        } else {
            delButtion.setVisibility(VISIBLE);
        }
    }

    protected void getAttrs(Context context, AttributeSet attrs){
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SimpleView);
        String validateTitle = a.getString(R.styleable.SimpleView_validateTitle);
        musicStatus.setText(validateTitle);
    }

    public void setValidateTitle(String name) {
        musicStatus.setText(name);
    }

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicService = ((MusicService.MyBinder)iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService = null;
        }
    };

    private void bindServiceConnection(Context context) {
        Intent intent = new Intent(context, MusicService.class);
        context.startService(intent);
        context.bindService(intent, sc, BIND_AUTO_CREATE);
    }

    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(musicService.mp.isPlaying()) {
                btnPlayOrPause.setText(R.string.playstopicon);
            } else {
                btnPlayOrPause.setText(R.string.playicon);
            }
            musicTime.setText(time.format(musicService.mp.getCurrentPosition()) + " / "
                    + time.format(musicService.mp.getDuration()));
            seekBar.setProgress(musicService.mp.getCurrentPosition());
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        musicService.mp.seekTo(seekBar.getProgress());
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            handler.postDelayed(runnable, 100);
        }
    };

    public void stop() {
        handler.removeCallbacks(runnable);
        try {
            getContext().unbindService(sc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(String url) {
        musicService = new MusicService();
        bindServiceConnection(getContext());
        musicService.start(url);
        handler.post(runnable);
        seekBar.setProgress(musicService.mp.getCurrentPosition());
        seekBar.setMax(musicService.mp.getDuration());
    }
}
